#!/usr/bin/python3
# -*- coding:utf-8 -*-
import sys
import os
from datetime import datetime
from datetime import timedelta
import socket
import random
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
festivallist = {
    '2021-02-11':'chuxi',
    '2021-02-12':'cnewyear',
    '2021-02-14':'valent',
    '2021-02-26':'yuanxiao',
    '2021-04-01':'yurenjie',
    '2021-05-01':'laodong',
    '2021-06-01':'ertong',
    '2021-07-01':'jiandang',
    '2021-09-21':'zhongqiu',
    '2021-10-01':'guoqing',
    '2021-12-25':'chrismas',
    '2022-01-01':'newyear'
}

import logging
import time
import traceback

logging.basicConfig(level=logging.DEBUG)

try:  
    now = datetime.now()
    today = now.strftime('%Y-%m-%d')
    if today in festivallist:
        special = festivallist.get(today)
    else:
        special = 'usual'
    
    bmpfiles = [os.path.splitext(x)[0] for x in os.listdir(picdir) if os.path.isfile(os.path.join(picdir,x)) and os.path.splitext(x)[1]=='.bmp']
    fileindex = [os.path.splitext(x)[0] for x in bmpfiles if os.path.splitext(x)[1]=='.b']
    filename = random.sample(fileindex, 1)[0]
    fileindex = [x for x in fileindex if os.path.splitext(x)[0]==special]
    print(fileindex)
    print(filename)

    if now.hour < 7:
        if (now.weekday() > 4) | (special != 'usual'):
            startuptime = now.replace(hour=12, minute=0, second=0, microsecond=0)
        else:
            startuptime = now.replace(hour=19, minute=0, second=0, microsecond=0)
    else:
        if (now.minute < 10) | (now.minute > 50):
            startuptime = (now + timedelta(minutes=30)).replace(minute=30, second=0, microsecond=0)
        else:
            startuptime = (now + timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
    
    # 发送定时启动信息
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 8423))
    s.send(('rtc_alarm_set ' + startuptime.strftime('%Y-%m-%dT%H:%M:%S+08:00') + ' 127').encode('ascii'))
    buffer = []
    while True:
        # 每次最多接收1k字节:
        d = s.recv(1024)
        if d:
            buffer.append(d)
        else:
            break
    data = b''.join(buffer)
    print(data)
    s.close()
    
    logging.info("Goto Sleep...")

except IOError as e:
    logging.info(e)
    
except KeyboardInterrupt:    
    logging.info("ctrl + c:")
    exit()